package com.example.javaproject.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.javaproject.dto.UserExcelDTO;
import com.example.javaproject.entity.Student;
import com.example.javaproject.entity.Teacher;
import com.example.javaproject.entity.User;
import com.example.javaproject.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserExcelServiceImpl implements UserExcelService {
    @Autowired
    private UserService userService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Override
    public void exportUsers(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户数据", StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 查询所有用户数据
        List<User> users = userService.list(new QueryWrapper<User>().eq("is_deleted", 0));
        List<UserExcelDTO> excelData = new ArrayList<>();

        // 转换数据格式
        for (User user : users) {
            UserExcelDTO dto = new UserExcelDTO();
            dto.setUsername(user.getUsername());
            dto.setPassword(user.getPassword());
            dto.setMail(user.getMail());
            dto.setPhone(user.getPhone());

            // 设置角色
            switch (user.getRole()) {
                case 0:
                    dto.setRole("管理员");
                    break;
                case 1:
                    dto.setRole("学生");
                    // 获取学生信息
                    Student student = studentService.getByUserId(user.getId());
                    if (student != null) {
                        dto.setName(student.getName());
                        dto.setCollege(student.getCollege());
                    }
                    break;
                case 2:
                    dto.setRole("教师");
                    // 获取教师信息
                    Teacher teacher = teacherService.getByUserId(user.getId());
                    if (teacher != null) {
                        dto.setName(teacher.getName());
                    }
                    break;
            }
            excelData.add(dto);
        }

        // 写入Excel
        EasyExcel.write(response.getOutputStream(), UserExcelDTO.class).sheet("用户数据").doWrite(excelData);
    }

    @Override
    @Transactional
    public int importUsers(MultipartFile file) throws IOException {
        List<UserExcelDTO> successList = new ArrayList<>();

        // 读取Excel数据
        EasyExcel.read(file.getInputStream(), UserExcelDTO.class, new PageReadListener<UserExcelDTO>(dataList -> {
            for (UserExcelDTO dto : dataList) {
                try {
                    // 创建用户
                    User user = new User();
                    user.setUsername(dto.getUsername());
                    user.setPassword(dto.getPassword());
                    user.setMail(dto.getMail());
                    user.setPhone(dto.getPhone());
                    user.setIsDeleted(0);
                    user.setCreateTime(LocalDateTime.now());
                    user.setUpdateTime(LocalDateTime.now());

                    // 设置角色
                    switch (dto.getRole()) {
                        case "管理员":
                            user.setRole(0);
                            break;
                        case "学生":
                            user.setRole(1);
                            break;
                        case "教师":
                            user.setRole(2);
                            break;
                        default:
                            continue;
                    }

                    // 保存用户
                    if (userService.save(user)) {
                        // 根据角色创建对应信息
                        if (user.getRole() == 1) { // 学生
                            Student student = new Student();
                            student.setUserId(user.getId());
                            student.setName(dto.getName());
                            student.setCollege(dto.getCollege());
                            student.setIsDeleted(0);
                            student.setCreateTime(LocalDateTime.now());
                            student.setUpdateTime(LocalDateTime.now());
                            studentService.save(student);
                        } else if (user.getRole() == 2) { // 教师
                            Teacher teacher = new Teacher();
                            teacher.setUserId(user.getId());
                            teacher.setName(dto.getName());
                            teacher.setIsDeleted(0);
                            teacher.setCreateTime(LocalDateTime.now());
                            teacher.setUpdateTime(LocalDateTime.now());
                            teacherService.save(teacher);
                        }
                        successList.add(dto);
                    }
                } catch (Exception e) {
                    // 记录失败信息，继续处理下一条
                    e.printStackTrace();
                }
            }
        })).sheet().doRead();

        return successList.size();
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户导入模板", StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 创建模板数据
        List<UserExcelDTO> templateData = new ArrayList<>();
        UserExcelDTO template = new UserExcelDTO();
        template.setUsername("请输入用户名");
        template.setPassword("请输入密码");
        template.setMail("请输入邮箱");
        template.setPhone("请输入电话");
        template.setRole("请输入角色（管理员/教师/学生）");
        template.setName("请输入姓名");
        template.setCollege("请输入学院（仅学生需要）");
        templateData.add(template);

        // 写入Excel
        EasyExcel.write(response.getOutputStream(), UserExcelDTO.class).sheet("模板").doWrite(templateData);
    }
} 